package com.imooc.sso.server;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

/**
 * 6.10.7 创建SsoAuthorizationServerConfig
 * @author qilongfei
 */
@Configuration
@EnableAuthorizationServer
public class SsoAuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

	/**
	 * 6.10.8 配置clients 认证服务器能给哪些应用发令牌
	 */
	@Override
	public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
		clients.inMemory()
			.withClient("imooc1")
			.secret("imoocsecret1")
			.authorizedGrantTypes("authorization_code", "refresh_token")
			.scopes("all")
			.and()
			.withClient("imooc2")
			.secret("imoocsecret2")
			.authorizedGrantTypes("authorization_code", "refresh_token")
			.scopes("all");
	}
	
	/**
	 * 6.10.9 处理token存储 拷贝6_9_2 
	 */
	@Bean
	public TokenStore jwtTokenStore(){
		return new JwtTokenStore(jwtAccessTokenConverter());
	}

	/**
	 * 6.10.10 处理token生成 指定一个秘钥，对它进行签名 拷贝6_9_3
	 */
	@Bean
	public JwtAccessTokenConverter jwtAccessTokenConverter(){
		JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter();
		accessTokenConverter.setSigningKey("imooc"); 
		return accessTokenConverter;
	}
	
	/**
	 * 6.10.11 配置endpoints 处理认证服务器token
	 */
	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
		endpoints.tokenStore(jwtTokenStore())
			.accessTokenConverter(jwtAccessTokenConverter());
	}
	
	/**
	 * 6.10.12 配置security 认证服务器的安全配置
	 * isAuthenticated() springsecurity的一个授权表达式
	 * 访问认证服务器获取用来签名的秘钥tokenKey的请求，必须经过身份认证
	 */
	@Override
	public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
		security.tokenKeyAccess("isAuthenticated()");
	}
}
